Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

  1. Given nums = [-2, 0, 3, -5, 2, -1]
  2. sumRange(0, 2) -> 1
  3. sumRange(2, 5) -> -1
  4. sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

Solution:

  1. public class NumArray {
  2. int[] sums;
  3. public NumArray(int[] nums) {
  4. sums = new int[nums.length];
  5. for (int i = 0; i < nums.length; i++)
  6. sums[i] = nums[i] + ((i > 0) ? sums[i - 1] : 0);
  7. }
  8. public int sumRange(int i, int j) {
  9. return (i == 0) ? sums[j] : sums[j] - sums[i - 1];
  10. }
  11. }
  12. // Your NumArray object will be instantiated and called as such:
  13. // NumArray numArray = new NumArray(nums);
  14. // numArray.sumRange(0, 1);
  15. // numArray.sumRange(1, 2);